﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using OrganizedIN.BAL;
using OrganizedIN.BussinessServices;
using System.IO;
using System.Data.SqlClient;
using Microsoft.ApplicationBlocks.Data;
namespace OrganizedIN.UI.Calendar
{
    public partial class Update_Calendar : System.Web.UI.Page
    {
        DateTime dt = DateTime.Now;

        private DataSet CalendarDetail { 
            get {
                return (DataSet)(ViewState["CalendarDetail"]);        
        } }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                save_button.Attributes.Add("onClick", "return CheckValidation()");
                lblTodayDate.Text = String.Format("{0:D}", dt);

                if (! Page.IsPostBack)
                {
                    if (Request.QueryString["CalendarID"] != null)
                    {
                        string CalendarID = Request.QueryString["CalendarID"];

                        DataSet ds = GetCalendarDetails(CalendarID);

                        if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                        {
                            ViewState["CalendarDetail"] = ds;

                            txtSummary.Text = Convert.ToString(ds.Tables[0].Rows[0]["Calendar_Summary"]);
                            txtshare.Text = Convert.ToString(ds.Tables[0].Rows[0]["Calendar_Share"]);
                            ddlImportType.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["Calendar_Import_Type"]);
                            string filename = Convert.ToString(ds.Tables[0].Rows[0]["Calendar_Path"]);
                            lblFilename.Text = filename.Substring(0, filename.Length - 19) + filename.Substring(filename.Length - 4, 4);
                       
                            save_button.Enabled = true;
                        }
                    }
                }                
            }
            catch (Exception ex)
            {
                lblErrMsg.Text = ex.Message;
            }
        }

        private DataSet GetCalendarDetails(string CalendarID)
        {
            SqlService objService = new SqlService();
            objService.AddParameter("@vcrCalendarID", ssenumSqlDataTypes.ssSDT_String, 10, CalendarID);

            return objService.RunProc("usp_Calendar_Get", "User_Calendar");
        }

        protected void save_button_Click(object sender, EventArgs e)
        {
            try
            {
                DataSet ds = (DataSet)CalendarDetail;
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    if (txtSummary.Text == Convert.ToString(ds.Tables[0].Rows[0]["Calendar_Summary"]) || ( ! IsCalendarExists()))
                    {
                        string filename = Convert.ToString(ds.Tables[0].Rows[0]["Calendar_Path"]);
                        string id = Convert.ToString(ds.Tables[0].Rows[0]["Calendar_ID"]);

                        if (FileUpload1.HasFile)
                        {
                            if (File.Exists(Path.Combine(Server.MapPath("~/CalendarUpload"), filename)))
                            {
                                File.Delete(Path.Combine(Server.MapPath("~/CalendarUpload"), filename));
                            }
                            //create the path to save the file to
                            filename = FileUpload1.FileName.Substring(0, FileUpload1.FileName.Length - 4) + "_" + dt.ToString("yyyyMMddHHmmss") + FileUpload1.FileName.Substring(FileUpload1.FileName.Length - 4, 4);

                            FileUpload1.SaveAs(Path.Combine(Server.MapPath("~/CalendarUpload"), filename));
                        }

                        UpdateCalendar(id, Convert.ToString(Session["UserID"]), dt, txtSummary.Text, filename, ddlImportType.SelectedValue, txtshare.Text);
                        Clear();
                        lblErrMsg.Text = "Record saved successfully.";
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "savesuccess", "<script>alert('Record saved successfully.');location.href='Search_Calendar.aspx';</script>", false);
                       // Response.Redirect("Search_Calendar.aspx");
                    }
                    else
                    {
                        throw new ApplicationException("Calendar already exists. Please provide different Calendar Summary.");
                    }
                }                
            }
            catch (Exception ex)
            {                lblErrMsg.Text = ex.Message;
            }
        }

        protected void Clear()
        {
            txtSummary.Text = "";
            txtshare.Text = "";
        }

        public static void UpdateCalendar(string CalendarID, string UserName, DateTime CalendarDate, string Calendar_Summary, 
            string CalendarPath, string CalendarType, string CalendarShare)
        {
            SqlService objservices = new SqlService();
            SqlParameter[] param = new SqlParameter[7];

            param[0] = new SqlParameter("@vcrCalendarID", SqlDbType.VarChar, 40);
            param[0].Value = CalendarID;

            param[1] = new SqlParameter("@vcrUserName", SqlDbType.VarChar, 40);
            param[1].Value = UserName;

            param[2] = new SqlParameter("@dtmCalendarDate", SqlDbType.DateTime);
            param[2].Value = CalendarDate;

            param[3] = new SqlParameter("@vcrCalendarSummary", SqlDbType.VarChar, 40);
            param[3].Value = Calendar_Summary;

            param[4] = new SqlParameter("@vcrCalendarPath", SqlDbType.VarChar, 40);
            param[4].Value = CalendarPath;

            param[5] = new SqlParameter("@vcrCalendarImportType", SqlDbType.VarChar, 100);
            param[5].Value = CalendarType;

            param[6] = new SqlParameter("@vcrCalendarShare", SqlDbType.VarChar, 100);
            param[6].Value = CalendarShare;

            SqlHelper.ExecuteNonQuery(objservices.ConnectionString, CommandType.StoredProcedure, "usp_Calendar_Update", param);

        }

        private bool IsCalendarExists()
        {
            bool isExist = false;

            SqlService objService = new SqlService();
            objService.AddParameter("@vcrUserName", ssenumSqlDataTypes.ssSDT_String, 40, Convert.ToString(Session["UserID"]));
            objService.AddParameter("@vcrSummary", ssenumSqlDataTypes.ssSDT_String, 40, txtSummary.Text);

            DataSet ds = objService.RunProc("usp_Calendar_AlreadyExists", "User_Calendar");

            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                isExist = true;
            }

            return isExist;
        }
    }
}
